﻿using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Plugin;
using Qdrant.Client.Grpc;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QdrantConnector
{
    [Icon("pack://application:,,,/QdrantConnector;component/Resources/Icon.png")]
    [Designer("QdrantConnector.Designer.QdrantConnectorServerCommandDesigner, QdrantConnector")]
    [Category("Qdrant向量数据库")]
    [OrderWeight(800)]
    public class CreateCollection : BaseQdrantOp
    {
        [ComboProperty]
        [DisplayName("距离计算方法")]
        [OrderWeight(100)]
        public Distance DistanceMethod { get; set; } = Distance.Cosine;

        [FormulaProperty]
        [DisplayName("向量长度")]
        [OrderWeight(110)]
        public object SizeExpr { get; set; } = 1024;

        public override async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var size = ulong.Parse((await dataContext.EvaluateFormulaAsync(this.SizeExpr))?.ToString() ?? "1024");

            var client = await getQrantClient(dataContext);
            var collectionName = await getCollectionName(dataContext);

            dataContext.Log.AppendLine($"开始在Qdrant中创建集合【{collectionName}】...");
            var tick = DateTime.Now;

            await client.CreateCollectionAsync(
                collectionName: collectionName,
                vectorsConfig: new VectorParams { Size = size, Distance = DistanceMethod }
            );

            dataContext.Log.AppendLine($"Qdrant集合【{collectionName}】创建成功，耗时：{(DateTime.Now - tick).TotalMilliseconds}ms");

            return new ExecuteResult();
        }

        public override string ToString()
        {
            return "Qdrant创建集合";
        }
    }


}
